﻿using System;
using System.Linq;
using System.Web;
using System.Web.UI;
using STP.Models;
using System.Security.Cryptography;
using System.Text;
using System.Data.SqlClient;
using System.Data;
using System.Diagnostics;
using System.IO;

namespace STP.Account
{
    public partial class ChangePassword : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session["user"] == null)
            {
                Session["returnUrl"] = Request.Url.ToString().Trim();
                Response.Redirect("~/user/Login");
            }
        }

        protected void submit_Click(object sender, EventArgs e)
        {
            DB db = new DB();
            if (rfv1.IsValid && rfv2.IsValid && rfv3.IsValid && rfv4.IsValid)
            {
                //检查旧密码是否正确
                string oldpassword = OldPassword.Text;
                string dbpassword = "";
                byte[] result = Encoding.Default.GetBytes(oldpassword);
                MD5 md5 = new MD5CryptoServiceProvider();
                byte[] output = md5.ComputeHash(result);
                oldpassword = BitConverter.ToString(output).Replace("-", "");
                SqlDataReader dr = db.ExceRead("select password from users where name='" + Session["user"].ToString().Trim() + "'");
                if (dr.Read()) dbpassword = dr["password"].ToString().Trim();
                dr.Close();
                if(dbpassword!=oldpassword)
                {
                    ErrorMessage.Text = "旧密码不正确";
                    return;
                }
                //存储新密码
                string password = Password.Text;
                result = Encoding.Default.GetBytes(password);
                md5 = new MD5CryptoServiceProvider();
                output = md5.ComputeHash(result);
                password = BitConverter.ToString(output).Replace("-", "");
                string sql = "update users set password='" + password + "' where name='" + Session["user"].ToString().Trim() + "'";
                db.ExceSql(sql);
                //注销
                Session["user"] = null;
                Response.Redirect("~/user/Login");
            }
        }

        protected void cancel_Click(object sender, EventArgs e)
        {
            Response.Redirect("~/index");
        }
    }
}